package com.tjakus.quartz;

import java.sql.Timestamp;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import com.tjakus.hibernate.Advertisement;
import com.tjakus.hibernate.HibernateUtil;
import com.tjakus.hibernate.Users;
import com.tjakus.http.HttpTrafficManager;
import com.tjakus.logging.Logging;
import com.tjakus.mail.MailOverHttp;

/**
 * This class represents quartz job which is responsible for sending e-mails to
 * the users.
 * 
 * @author tjakus
 * 
 */

public class JobSendMail implements Job {

	/**
	 * This method executes quartz job which is responsible for sending e-mails to
	 * the users.
	 * 
	 */
	public void execute(JobExecutionContext context) throws JobExecutionException {

		MailOverHttp mail = new MailOverHttp();
		List<Users> users;
		String messageBody = "";
		String subject = "";
		boolean status;

		Logging.getLogger().info("JobSendMail - execute [ STARTED ]");

		// Initialize HttpTrafficManager for sending HTTP requests
		HttpTrafficManager.initializeHttpTrafficManager();
		// Log in to e-mail account
		status = mail.logInToEmailAccount();
		if (!status) {
			Logging.getLogger().error("JobSendMail - execute [ UNABLE TO LOG IN ]");
			return;
		}

		// Current time stamp
		Date date = new Date();
		Timestamp currentTimestamp = new Timestamp(date.getTime());
		users = HibernateUtil.getAllUsers();
		for (Iterator<Users> iter = users.iterator(); iter.hasNext();) {
			Users user = iter.next();
			List<Integer> serviceIds = HibernateUtil
					.getMappingServiceIdsFromUser(user.getEmail());
			// if user has services
			if (!(serviceIds == null)) {
				if (serviceIds.iterator().hasNext()) {
					// Get the users advertisements newer then users time stamp
					List<Advertisement> advertisements = HibernateUtil
							.getAdvertisementsByTimestampAndServiceIds(
									user.getLastTimestamp(), serviceIds);
					// if there are new entries in advertisement table send mail
					if (!(advertisements == null)) {
						if (advertisements.iterator().hasNext()) {
							messageBody = this.createMessageBody(advertisements);
							// Add only date to message subject
							subject = "NjuskaloWeb - "
									+ user.getLastTimestamp().toString().substring(0, 10);
							boolean mailStatus = mail.postMail(user, subject, messageBody);
							// If mail has been sent successfully
							if (mailStatus) {
								// Update user time stamp in users table and mail counter
								user.setLastTimestamp(currentTimestamp);
								user.setMailCounter(user.getMailCounter() + 1);
								HibernateUtil.updateUsers(user);
							}
							// No new entries in advertisement table for user
						} else {
							// Just update users time stamp, don't increase mail counter
							user.setLastTimestamp(currentTimestamp);
							HibernateUtil.updateUsers(user);
						}

					}
				}
			}
		}
		// Log out from e-mail account
		mail.logOutFromEmailAccount();

		// HttpTrafficManager - close all HTTP connections
		HttpTrafficManager.closeAllConnections();
		Logging.getLogger().info("JobSendMail - execute [ FINISHED ]");
	}

	/**
	 * This method creates e-mail body from list of advertisements
	 * 
	 */
	private String createMessageBody(List<Advertisement> advertisements) {

		String messageBody = "";

		for (Iterator<Advertisement> iter = advertisements.iterator(); iter
				.hasNext();) {
			Advertisement advertisement = iter.next();
			messageBody = messageBody
					+ "%3Cp%3E---------------------------------------------------------%3C%2Fp%3E";
			Logging.getLogger().debug(
					"JobSendMail - execute  - TITLE - [ " + advertisement.getTitle()
							+ " ]");
			messageBody = messageBody + "%3Cp%3ETITLE: " + advertisement.getTitle()
					+ "%3C%2Fp%3E";
			Logging.getLogger().debug(
					"JobSendMail - execute  - URL - [ " + advertisement.getUrl() + " ]");
			messageBody = messageBody + "%3Cp%3EURL: " + advertisement.getUrl()
					+ "%3C%2Fp%3E";
			Logging.getLogger().debug(
					"JobSendMail - execute  - DESCRIPTION - [ "
							+ advertisement.getDescription() + " ]");
			messageBody = messageBody + "%3Cp%3EDESCRIPTION: "
					+ advertisement.getDescription() + "%3C%2Fp%3E";
			Logging.getLogger()
					.debug(
							"JobSendMail - execute  - DATE - [ " + advertisement.getDate()
									+ " ]");
			messageBody = messageBody + "%3Cp%3EDATE: " + advertisement.getDate()
					+ "%3C%2Fp%3E";
			Logging.getLogger().debug(
					"JobSendMail - execute  - PRICE - [ " + advertisement.getPrice()
							+ " ]");
			messageBody = messageBody + "%3Cp%3EPRICE: " + advertisement.getPrice()
					+ "%3C%2Fp%3E";
		}
		return messageBody;
	}
}
